package com.zyg.demo.entity;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.support.v7.content.res.AppCompatResources;
import android.text.TextUtils;
import android.util.AttributeSet;

import com.bumptech.glide.Glide;
import com.zyg.demo.R;
import com.zyg.demo.listener.AnimatorListener;
import com.zyg.demo.util.Constants;

import java.util.ArrayList;
import java.util.List;


/**
 * @author zhengyunguang
 * created at 2019-07-10 22:18
 */
public class PluginFolderView extends android.support.v7.widget.AppCompatImageView {

    private static final int ROW = 2;
    private static final int COLUMN = 2;
    private static final int PIXEL_CAP = 4;
    private static final int PADDING = 10;
    private static final int CAPACITY = ROW * COLUMN;


    private Paint bgPaint;

    /**
     * 当所有子item动画结束时，提供给外部动画结果
     */
    private AnimatorListener animatorListener;
    /**
     * 插件icons
     */
    private List<Drawable> drawables;
    /**
     * 插件
     */
    private Plugin plugin;


    public PluginFolderView(Context context) {
        super(context);
        init();
    }

    public PluginFolderView(Context context, AttributeSet attributeset) {
        super(context, attributeset);
        init();
    }

    private void init() {
        bgPaint = new Paint();
        bgPaint.setAntiAlias(true);
        bgPaint.setColor(getResources().getColor(R.color.light_gray));
        bgPaint.setStyle(Paint.Style.FILL);
    }

    public void setAnimatorListener(AnimatorListener animatorListener) {
        this.animatorListener = animatorListener;
    }

    public void setPlugin(Plugin plugin) {
        if (plugin == null) {
            setDefaultIcon();
            return;
        }
        this.plugin = plugin;
        if (plugin.type == Constants.TYPE_PLUGIN) {
            setIconPlugin();
        } else {
            setIconFolder();
        }
    }

    private void setIconPlugin() {
        if (plugin.imageItem != null) {
            if (plugin.imageItem.res > 0) {
                Glide.with(getContext())
                        .load(plugin.imageItem.res)
                        .into(this);
            } else if (!TextUtils.isEmpty(plugin.imageItem.url)) {
                Glide.with(getContext())
                        .load(plugin.imageItem.url)
                        .placeholder(R.drawable.plugin_default_icon)
                        .into(this);
            } else {
                setDefaultIcon();
            }
        } else {
            setDefaultIcon();
        }
    }

    private SubPluginShowItem pluginShowItem;

    private void setIconFolder() {
        if (pluginShowItem != null) {
            return;
        }
        List<ImageItem> imageItems = plugin.imageItems;
        if (imageItems != null && imageItems.size() > 0) {
            if (drawables != null) {
                drawables.clear();
                drawables = null;
            }
            int size = Math.min(imageItems.size(), CAPACITY);
            drawables = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                ImageItem imageItem = imageItems.get(i);
                drawables.add(i, AppCompatResources.getDrawable(getContext(), imageItem.res));
            }
            if (plugin.dragState != Constants.DRAW_STATE_NORMAL) {
                if (plugin.dragState == Constants.DRAW_STATE_ADDING) {
                    int tempSize = imageItems.size();
                    if (tempSize <= CAPACITY) {
                        pluginShowItem = new SubPluginShowItem(tempSize - 1);
                    } else {
                        invalidate();
                    }
                } else {
                    pluginShowItem = new SubPluginShowItem(-1);
                }
                if (pluginShowItem != null) {
                    pluginShowItem.setAnimatorListener(innerAnimatorListener);
                    pluginShowItem.start();
                }
            } else {
                invalidate();
            }
        } else {
            setDefaultIcon();
        }
    }

    private AnimatorListener innerAnimatorListener = new AnimatorListener() {
        @Override
        public void onAnimatorFinish() {
            if (plugin != null) {
                plugin.dragState = Constants.DRAW_STATE_NORMAL;
            }
            pluginShowItem = null;
            if (animatorListener != null) {
                animatorListener.onAnimatorFinish();
            }
        }

        @Override
        public void onAnimatorUpdate(ValueAnimator animation) {
            invalidate();
        }
    };

    private void setDefaultIcon() {
        Glide.with(getContext()).load(R.drawable.plugin_default_icon).into(this);
    }


    //todo 处理网络情况
//    public void setIcons(List<ImageItem> items){
//        type = Constants.TYPE_FOLDER;
//        if(items != null && items.size() > 0){
//            if(drawables != null){
//                drawables.clear();
//                drawables = null;
//            }
//            drawables = new ArrayList<>(items.size());
//            for (ImageItem item : items) {
//                if(item.res > 0){
//                    Glide.with(getContext()).load(item.res).into(new SimpleTarget<GlideDrawable>() {
//                        @Override
//                        public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
//                            drawables.add(resource);
//                        }
//                    });
//                } else if(!TextUtils.isEmpty(item.url)){
//                    Glide.with(getContext()).load(item.url).into(new SimpleTarget<GlideDrawable>() {
//                        @Override
//                        public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
//                            drawables.add(resource);
//                        }
//                    });
//                }else {
//                    Glide.with(getContext()).load(R.drawable.plugin_default_icon).into(new SimpleTarget<GlideDrawable>() {
//                        @Override
//                        public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
//                            drawables.add(resource);
//                        }
//                    });
//                }
//            }
//        }
//    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (plugin.type == Constants.TYPE_FOLDER) {
            drawBackground(canvas);
            drawImages(canvas);
        } else if(plugin.type == Constants.TYPE_HOLDER){
            //todo do nothing

        } else {
            super.onDraw(canvas);
        }
    }

    private void drawBackground(Canvas canvas) {
        RectF rect = new RectF();
        float scale = 1f;
        if (pluginShowItem != null) {
            if (pluginShowItem.pos == -1) {
                scale = pluginShowItem.scale;
            }
        }
        int width = getWidth();
        int height = getHeight();
        float left = ((1 - scale) * width) / 2;
        float top = ((1 - scale) * height) / 2;
        float right = left + width * scale;
        float bottom = top + height * scale;
        rect.set(left, top, right, bottom);
        canvas.drawRoundRect(rect, 30, 30, bgPaint);
    }

    private void drawImages(Canvas canvas) {
        int width = getWidth();
        int height = getHeight();

        int cellWidth = (width - PADDING * 2 - (PIXEL_CAP * (COLUMN + 1))) / COLUMN;
        int cellHeight = (height - PADDING * 2 - (PIXEL_CAP * (ROW + 1))) / ROW;

        out:
        for (int i = 0; i < ROW; i++) {
            for (int j = 0; j < COLUMN; j++) {
                int index = i * COLUMN + j;
                if (index >= drawables.size() || index >= ROW * COLUMN) {
                    break out;
                }
                Drawable drawable = drawables.get(index);
                float scale = 1f;
                if (pluginShowItem != null) {
                    if (pluginShowItem.pos == -1) {
                        scale = pluginShowItem.scale;
                    } else {
                        if (index == pluginShowItem.pos) {
                            scale = pluginShowItem.scale;
                        }
                    }
                }
                int left = PADDING + (j + 1) * PIXEL_CAP + j * cellWidth;
                int top = PADDING + (i + 1) * PIXEL_CAP + i * cellHeight;
                int halfScaleWidth = (int) (((1 - scale) * cellWidth) / 2);
                int halfScaleHeight = (int) (((1 - scale) * cellHeight) / 2);
                int scaleLeft = left + halfScaleWidth;
                int scaleTop = top + halfScaleHeight;
                int scaleRight = (int) (scaleLeft + cellWidth * scale);
                int scaleBottom = (int) (scaleTop + cellHeight * scale);
                drawable.setBounds(scaleLeft, scaleTop, scaleRight, scaleBottom);
                drawable.draw(canvas);
            }
        }

    }
}
